const express=require("express");
const handleDB=require("../db/handleDB");
const common=require("../utils/common");
const constant=require("../utils/constant");
const md5=require("md5");
const Captcha=require("../utils/captcha");
const keys = require("../utils/keys");
const jwt=require("jsonwebtoken");
require("../utils/filter");

const router=express.Router();

router.get("/commodity_detail/:commodity_id",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUser(req,res);

        //购物车的数量
        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }

        //销量排行
        let salesOrder=await handleDB(res,"commodity","find","查询数据库出错","1 order by sales_volume desc limit 6")

        //商品详情页数据
        let {commodity_id}=req.params;
        let commodityId=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${commodity_id}`);
        if(!commodityId[0]){
            common.abort404(req,res);
            return
        }

        let merchantInfo=await handleDB(res,"user","find","数据库查询出错",`user_id=${commodityId[0].merchant_id}`)

        //商品评论的数量
        let commentCounts=await handleDB(res,"comment","sql","数据库查询出错",`select count(*) from comment where commodity_id=${commodityId[0].commodity_id}`);

        //用户评论的信息
        let commentInfo=await handleDB(res,"comment","find","查询数据库出错",`commodity_id=${commodityId[0].commodity_id} order by create_time desc`)


        for(let i=0;i<commentInfo.length;i++){
            let commenteUser=await handleDB(res,"user","find","查询数据库出错",`user_id=${commentInfo[i].user_id}`)

            commentInfo[i].commenter={
                nick_name:commenteUser[0].nick_name,
                head_url:commenteUser[0].head_url?commenteUser[0].head_url:"/news/images/worm.jpg"
            }

            if(commentInfo[i].parent_id){
                var parentComment=await handleDB(res,"comment","find","数据库查询失败",`comment_id=${commentInfo[i].parent_id}`)
                var parentUserInfo=await handleDB(res,"user","find","数据库查询失败",`user_id=${parentComment[0].user_id}`)

                commentInfo[i].parent={
                    user:{
                        nick_name:parentUserInfo[0].nick_name
                    },
                    content:parentComment[0].content
                }
            }
        }

        let user_like_comments_ids=[];
        if(userInfo[0]){
            let user_like_commentsResult=await handleDB(res,"comment_like","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)

            user_like_commentsResult.forEach(el=>{
                user_like_comments_ids.push(el.comment_id)
            })
        }

        let isCollected=false;
        if(userInfo[0]){
            let collectionResult=await handleDB(res,"collect","find","查询数据库出错",`user_id=${userInfo[0].user_id} and commodity_id=${commodity_id}`)
            if(collectionResult[0]){
                isCollected=true;
            }
        }

        let isFollow=false;
        if(userInfo[0]){
            let followResult=await handleDB(res,"concern","find","查询数据库出错",`user_id=${userInfo[0].user_id} and merchant_id=${merchantInfo[0].user_id}`)
            if(followResult[0]){
                isFollow=true;
            }
        }

        let data={
            user_info:userInfo[0]?{
                user_id:userInfo[0].user_id,
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            commodityId:commodityId[0],
            number:number,
            isCollected,
            salesOrder:salesOrder,
            merchantInfo:merchantInfo[0],
            commentCounts:commentCounts[0]["count(*)"],
            commentInfo:commentInfo,
            user_like_comments_ids,
            isFollow
        }
        res.render("./web_detail",data);
    })();
})

router.post("/commodity_detail/commodity_comment",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {commodity_id,comment,parent_id=null}=req.body;
        if(!commodity_id||!comment){
            res.send({errmsg:"参数错误1"})
            return
        }
        
        let commodityResult=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${commodity_id}`)
        if(!commodityResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        let commentObj={
            user_id:userInfo[0].user_id,
            commodity_id,
            content:comment,
            create_time:new Date().toLocaleString('chinese',{hour12:false})
        }
        if(parent_id){
            commentObj.parent_id=parent_id

            var parentComment=await handleDB(res,"comment","find","数据库查询出错",`comment_id=${parent_id}`)

            var parentUserInfo=await handleDB(res,"user","find","数据库查询失败",`user_id=${parentComment[0].user_id}`)
        }

        let insertResult=await handleDB(res,"comment","insert","数据库插入失败",commentObj);
        console.log(insertResult.insertId)

        let data={
            user:{
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg",
                nick_name:userInfo[0].nick_name
            },
            content:comment,
            create_time:commentObj.create_time,
            commodity_id,
            id:insertResult.insertId,
            parent:parent_id?{
                user:{
                    nick_name:parentUserInfo[0].nick_name
                },
                content:parentComment[0].content
            }:null
        }
        res.send({errno:'0',errmsg:"操作成功",data})
    })();
})

router.post("/commodity_detail/comment_like",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {comment_id,action}=req.body;
        if(!comment_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        let commentResult=await handleDB(res,"comment","find","数据库查询出错",`comment_id=${comment_id}`)
        if(!commentResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="add"){
            await handleDB(res,"comment_like","insert","数据库添加出错",{
                comment_id,
                user_id:userInfo[0].user_id
            })
            var like_num=commentResult[0].like_num?commentResult[0].like_num+1:1
        }else{
            await handleDB(res,"comment_like","delete","数据库删除出错",`comment_id=${comment_id} and user_id=${userInfo[0].user_id}`)
            var like_num=commentResult[0].like_num?commentResult[0].like_num-1:0
        }

        await handleDB(res,"comment","update","数据库更新失败",`comment_id=${comment_id}`,{like_num})

        res.send({errno:"0",errmsg:"操作成功"})
        
    })();
})

router.post("/commodity_detail/commodity_collect",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {commodity_id,action}=req.body;
        if(!commodity_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        let commodityResult=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${commodity_id}`);
        if(!commodityResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="collect"){
            await handleDB(res,"collect","insert","数据库添加失败",{
                user_id:userInfo[0].user_id,
                commodity_id
            })
        }else{
            await handleDB(res,"collect","delete","数据库删除失败",`user_id=${userInfo[0].user_id} and commodity_id=${commodity_id}`)
        }
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})

router.post("/merchantInfo_detail/concern_merchantInfo",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);

        if(!userInfo[0]){
            res.send({errno:"4101",errmsg:"用户未登录"})
            return
        }

        let {user_id,action}=req.body;
        if(!user_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        if(user_id==userInfo[0].user_id){
            res.send({errmsg:"用户自己不能关注自己的文章"})
            return
        }
        let userResult=await handleDB(res,"user","find","数据库查询出错",`user_id=${user_id}`);
        if(!userResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="follow"){
            await handleDB(res,"concern","insert","数据库添加失败",{
                user_id:userInfo[0].user_id,
                merchant_id:user_id
            })
        }else{
            await handleDB(res,"concern","delete","数据库删除失败",`user_id=${userInfo[0].user_id} and merchant_id=${user_id}`)
        }
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})

router.get("/web_commodity_pay/",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {commodity_id,commodity_number}=req.query
        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }

        let receiving_address=await handleDB(res,"receiving_address","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)

        if(receiving_address[0]==undefined){
            receiving_address=0;
        }

        let commodity=await handleDB(res,"commodity","find","数据库查询出错2",`commodity_id=${commodity_id}`)
        let merchant=await handleDB(res,"user","find","数据库查询出错2",`user_id=${commodity[0].merchant_id}`)
        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            number:number,
            receiving_address,
            merchant:merchant[0].nick_name,
            commodity:commodity[0],
            commodity_number
        };
        res.render("./web_commodity_pay",data);
    })();
})

router.post("/web_commodity_pay/add",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {commodity_id,merchant_id,number,address_id}=req.body

        let merchant=await handleDB(res,"user","find","数据库查询出错",`user_id=${merchant_id}`)
        let commodity=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${commodity_id}`)
        let price=Number(commodity[0].unit_price)*Number(number)
        if(userInfo[0].money<price){
            res.send({errno:"4101",errmsg:"余额不足！"})
            return
        }
        await handleDB(res,"indent","insert","数据库插入出错",{
            user_id:userInfo[0].user_id,
            commodity_id,
            merchant_id,
            order_time:new Date().toLocaleString('chinese',{hour12:false}),
            number,
            is_order:1,
            address_id
        })
        await handleDB(res,"commodity","update","数据库更新失败",`commodity_id=${commodity_id}`,{
            sales_volume:Number(commodity[0].sales_volume)+Number(number)
        })
        await handleDB(res,"user","update","数据库更新失败",`user_id=${userInfo[0].user_id}`,{
            money:Number(userInfo[0].money)-Number(price)
        })
        await handleDB(res,"user","update","数据库更新失败",`user_id=${merchant[0].user_id}`,{
            money:Number(merchant[0].money)+Number(price)
        })
        res.send({errno:"0",errmsg:"购买成功！"})
    })();
})

router.post("/web_detail/web_shopping_cart/",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        if(!userInfo[0]){
            res.send({errmsg:"参数错误2"})
            return
        }
        let {commodity_id,commodity_number}=req.body

        let commodity=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${commodity_id}`)
        await handleDB(res,"indent","insert","数据库插入出错",{
            user_id:userInfo[0].user_id,
            commodity_id,
            merchant_id:commodity[0].merchant_id,
            order_time:new Date().toLocaleString('chinese',{hour12:false}),
            number:commodity_number,
            is_order:0
        })
        res.send({errno:"0",errmsg:"添加购物车成功！"})
    })();
})

router.post("/web_shopping_cart/add",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {indent_id,address_id,price,indent_id_num}=req.body
        if(!indent_id || !address_id || !price ||!indent_id_num){
            res.send({errmsg:"参数错误1"})
            return
        }
        if(userInfo[0].money<price){
            res.send({errno:"4101",errmsg:"余额不足！"})
            return
        }
        let id=indent_id.split('/')
        let id_num=indent_id_num.split('/')

        
        await handleDB(res,"user","update","数据库更新失败",`user_id=${userInfo[0].user_id}`,{
            money:Number(userInfo[0].money)-Number(price)
        })
        for(var i=1;i<id.length;i++){
            await handleDB(res,"indent","update","数据库更新失败",`indent_id=${id[i]}`,{
                is_order:1,
                address_id,
                number:id_num[i]
            })
            let indent=await handleDB(res,"indent","find","数据库查询出错",`indent_id=${id[i]}`)
            let commodity=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${indent[0].commodity_id}`)
            let merchant=await handleDB(res,"user","find","数据库查询出错",`user_id=${indent[0].merchant_id}`)
            await handleDB(res,"user","update","数据库更新失败",`user_id=${indent[0].merchant_id}`,{
                money:Number(merchant[0].money)+Number(indent[0].number)*Number(commodity[0].unit_price)
            })

            await handleDB(res,"commodity","update","数据库更新失败",`commodity_id=${indent[0].commodity_id}`,{
                sales_volume:Number(commodity[0].sales_volume)+Number(id_num[i])
            })
        }
        res.send({errno:"0",errmsg:"购买成功！"})
    })();
})


router.get("/shopping_cart/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let indent=await handleDB(res,"indent","find","数据库查询出错",`user_id=${userInfo[0].user_id} and is_order=0`)
        for(var i=0;i<indent.length;i++){
            let commodity=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${indent[i].commodity_id}`)
            indent[i].commodity_name=commodity[0].commodity_name
            indent[i].commodity_url=commodity[0].commodity_url
            indent[i].unit_price=commodity[0].unit_price
            indent[i].price=Number(commodity[0].unit_price)*Number(indent[i].number)
        }

        let receiving_address=await handleDB(res,"receiving_address","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)

        if(receiving_address[0]==undefined){
            receiving_address=0;
        }

        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }
        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            number:number,
            receiving_address,
            indent
        };
        res.render("./web_shopping_cart",data);
    })();
})

router.post("/web_shopping_cart/alldel",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {indent_id}=req.body
        if(!indent_id){
            res.send({errmsg:"参数错误1"})
            return
        }
        let id=indent_id.split('/')
        for(var i=1;i<id.length;i++){
            await handleDB(res,"indent","delete","数据库删除出错",`indent_id=${id[i]}`)
        }
        
        res.send({errno:"0",errmsg:"删除成功！"})
    })();
})

router.post("/web_shopping_cart/del",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {indent_id}=req.body
        if(!indent_id){
            res.send({errmsg:"参数错误1"})
            return
        }
        await handleDB(res,"indent","delete","数据库删除出错",`indent_id=${indent_id}`)
        res.send({errno:"0",errmsg:"删除成功！"})
    })();
})

router.get("/web_merchant/:merchant_id",(req,res)=>{
    (async function(){
        let userInfo=await common.getUser(req,res);
        
        let {merchant_id}=req.params;
        if(!merchant_id){
            res.send({errmsg:"参数错误1"})
            return
        }
        let merchantInfo=await handleDB(res,"user","find","数据库查询出错",`user_id=${merchant_id}`)
        if(!merchantInfo[0]){
            common.abort404(req,res);
            return
        }
        let concernCounts=await handleDB(res,"concern","sql","数据库查询出错",`select count(*) from concern where merchant_id=${merchant_id}`);
        let classify=await handleDB(res,"classify","find","数据库查询出错");
        let commodity=await handleDB(res,"commodity","find","数据库查询出错",`merchant_id=${merchant_id}`)
        for(var i=0;i<commodity.length;i++){
            let collects=await handleDB(res,"collect","sql","数据库查询出错",`select count(*) from collect where commodity_id=${commodity[i].commodity_id}`)
            commodity[i].collects=collects[0]["count(*)"];
        }
        
        let isFollow=false;
        if(userInfo[0]){
            let followResult=await handleDB(res,"concern","find","查询数据库出错",`user_id=${userInfo[0].user_id} and merchant_id=${merchantInfo[0].user_id}`)
            if(followResult[0]){
                isFollow=true;
            }
        }

        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }
        let salesOrder=await handleDB(res,"commodity","find","查询数据库出错","1 order by sales_volume desc limit 6")
        let data={
            user_info:userInfo[0]?{
                user_id:userInfo[0].user_id,
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            number:number,
            classify,
            salesOrder:salesOrder,
            merchantInfo:merchantInfo[0],
            concernCounts:concernCounts[0]["count(*)"],
            commodity,
            isFollow
        };
        res.render("./web_merchant",data);
    })();
})

router.post("/web_merchant/show",(req,res)=>{
    (async function(){
        let {classify_id,merchant_id}=req.body
        if(!classify_id || !merchant_id){
            res.send({errmsg:"参数错误1"})
            return
        }
        let commodity=await handleDB(res,"commodity","find","数据库查询出错",`merchant_id=${merchant_id} and classify_id=${classify_id}`)
        for(var i=0;i<commodity.length;i++){
            let collects=await handleDB(res,"collect","sql","数据库查询出错",`select count(*) from collect where commodity_id=${commodity[i].commodity_id}`)
            commodity[i].collects=collects[0]["count(*)"];
        }
        res.send({
            commodity
        })
    })();
})

router.get("/web_private_letter/",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {merchant_id,user_id}=req.query
        let merchant=await handleDB(res,"user","find","数据库查询出错",`user_id=${merchant_id} and is_merchant=1`)
        let user=await handleDB(res,"user","find","数据库查询出错",`user_id=${user_id}`)
        user[0].head_url=user[0].head_url?user[0].head_url:"/images/worm.jpg"
        if(!merchant[0] || !user[0]){
            common.abort404(req,res);
            return
        }

        let private_letter=await handleDB(res,"private_letter","find","数据库查询出错",`(speak_id=${user_id} and receive_id=${merchant_id}) or (speak_id=${merchant_id} and receive_id=${user_id})`)
        if(private_letter[0]==undefined){
            private_letter=0
        }
        for(var i=0;i<private_letter.length;i++){
            if(private_letter[i].speak_id==user[0].user_id){
                private_letter[i].is=1;
            }
            else{
                private_letter[i].is=0;
            }
        }

        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }
        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            number:number,
            merchant,
            user,
            private_letter
        };
        res.render("./web_private_letter",data);
    })();
})

router.post("/web_private_letter/add",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {merchant_id,user_id,content}=req.body
        if(!merchant_id || !user_id ||!content){
            res.send({errmsg:"参数错误1"})
            return
        }
        await handleDB(res,"private_letter","insert","数据库添加出错",{
            speak_id:user_id,
            receive_id:merchant_id,
            content
        })
        res.send({errno:"0",errmsg:"删除成功！"})
    })();
})


module.exports=router